package BFS解决FloodFill算法;

import java.util.LinkedList;
import java.util.Queue;

public class test2 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    boolean[][] flag = new boolean[301][301]; // 用来记录当前位置是否已经被算为了岛屿,true 已标记
    int n,m;
    public int numIslands(char[][] grid) {
        n = grid.length;
        m = grid[0].length;
        int ret = 0; // 记录岛屿数量

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid[i][j] == '1'&& !flag[i][j]){
                    ret++;
                    bfs(grid,i,j); //进行宽搜
                }
            }
        }
        return ret;
    }
    public void bfs(char[][]grig,int sr,int sc){
        Queue<int[]> queue  = new LinkedList<>();
        queue.add(new int[]{sr,sc}); // 记录当前位置
        flag[sr][sc] = true;

        while (!queue.isEmpty()){
            int[] arr = queue.poll();
            int a=arr[0],b=arr[1];
            for (int i = 0; i < 4; i++) {
                int x = a+dx[i];
                int y = b+dy[i];
                if(x>=0&&x<n&&y>=0&&y<m&&grig[x][y]=='1'&&!flag[x][y]) {
                    queue.add(new int[]{x, y});
                    flag[x][y] = true;
                }
            }
        }
    }
}
